package com.framewiki.example.service;

import com.cdkjframework.datasource.jpa.builder.JpaCriteriaBuilder;
import com.cdkjframework.oauth2.entity.AuthorizationCode;
import com.cdkjframework.oauth2.repository.AuthorizationCodeRepository;
import com.cdkjframework.util.make.GeneratedValueUtils;
import com.cdkjframework.util.tool.CopyUtils;
import com.framewiki.example.entity.RmsAuthorizationCodesEntity;
import com.framewiki.example.repository.RmsAuthorizationCodeRepository;

import lombok.RequiredArgsConstructor;

import java.util.Optional;

import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class AuthorizationCodeRepositoryImpl implements AuthorizationCodeRepository {

    private final RmsAuthorizationCodeRepository rmsAuthorizationCodeRepository;

    @Override
    public AuthorizationCode findByCode(String code) {
        JpaCriteriaBuilder<RmsAuthorizationCodesEntity> builder = JpaCriteriaBuilder.Builder();
        builder = builder.equal(RmsAuthorizationCodesEntity.CODE, code);

        Optional<RmsAuthorizationCodesEntity> optional = rmsAuthorizationCodeRepository.findOne(builder.build());

        if (!optional.isPresent()) {
            return null;
        } else {
            RmsAuthorizationCodesEntity entity = optional.orElse(null);
            if (entity == null) {
                return null;
            }
            rmsAuthorizationCodeRepository.deleteById(entity.getId());
            return CopyUtils.copyNoNullProperties(optional.orElse(null), AuthorizationCode.class);
        }
    }

    @Override
    public void save(AuthorizationCode authorizationCode) {
        RmsAuthorizationCodesEntity entity = CopyUtils
                .copyNoNullProperties(authorizationCode, RmsAuthorizationCodesEntity.class);
        entity.setId(GeneratedValueUtils.getMonotonicUlidString());
        rmsAuthorizationCodeRepository.save(entity);
    }

}